<template>
  <div class="biz-comment-at" @click.stop>
    <div 
      class="base-comment" :class="{'base-comment-focus': inputState}"
      @mousedown.stop="mousedown"
      @mouseup="mouseup"
      @keydown.enter.stop="enterDown" tabindex="0">
      <div class="base-comment-inner" v-show="inputState">

        <!-- start 模板列表 -->
        <div class="select-template" v-if="showSelectTemplate">
          <label>{{$t('component.bizComment.label1')}}</label>
          <el-select
            :value="template"
            :placeholder="$t('component.bizComment.placeholder1')"
            @input="selectTemplateChange"
          >
            <el-option
              v-for="item in templateListOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <!-- end 模板列表 -->

        <!-- start textarea -->
        <biz-at-textarea ref="atTextarea" v-if="isAt" :members="members" :search-url="userSearchUrl" name-key="displayName" v-model="form.content" :at-users.sync="atUsers" :search-params="searchParams">
          <template slot="item" slot-scope="item">
            <img :src="head(item.user.head)">
            <span>{{item.user.displayName}}</span>
          </template>
          <textarea ref="editor" class="base-comment-editor" :style="editorCalcStyle" @input="inputContent" :placeholder="`${placeholder}${$t('component.bizComment.placeholder2')}`" maxlength="500"></textarea>
        </biz-at-textarea>
        <textarea 
          v-else
          ref="editor" 
          class="base-comment-editor" :style="editorCalcStyle"
          :placeholder="`${placeholder}`" 
          maxlength="500"
          :value="form.content" @input="inputContent"
        />
        <!-- start textarea -->

        <!-- start 附件列表 -->
        <div class="base-comment-attachment base-file__preview" v-if="form.attachments.length > 0">
          <base-file-item v-for="file in form.attachments" :source="form.attachments" :key="file.id" :file="file" @delete="deleteFile" size="small" formEditingMode="create"></base-file-item>
        </div>
        <!-- end 附件列表 -->

        <!-- start 底部操作 -->
        <div class="base-comment-footer">
          <div class="base-comment-toolbar">
            <button type="button" class="base-comment-tool" @click="chooseFile">
              <i class="iconfont icon-attachment"></i> {{$t('common.base.attachment')}}
            </button>
            &nbsp;
            <button type="button" class="base-comment-tool" @click="addAt" style="font-size:16px;" v-if="isAt">
              @
            </button>
          <!-- <span class="base-comment-err" v-if="errMessage">{{errMessage}}</span> -->
          </div>
        
          <!-- start 操作组 -->
          <div class="base-comment-bottom">
            <!-- <div class="base-comment-title">可见范围</div> -->

            <div class="base-comment-action">
              <el-checkbox v-model="form.showInOwn" @input="showInOwnChangeHandler" :disabled="checkboxDisabled.showInOwn" :true-label="1" :false-label="0">{{$t('common.option.commentAction[0]')}}</el-checkbox>
              <template v-if="showCustomerAction">
                <el-popover v-model="noteToCustomer" placement="top" :width="240">
                  <div>
                    <div class="flex-x jus-end just-cur-point" @click="noteToCustomer = false"><i class="iconfont icon-close"></i></div>
                    <div class="mar-b-16">{{ $t('task.commonWithMobile.remarkNoteToCustomerTips') }}</div>
                    <div class="flex-x al-center">
                      <div class="flex-1">
                        <el-checkbox v-model="hideTipsCheck" @change="(e)=>$emit('changeHideTips', e)">{{ $t('task.commonWithMobile.btn1') }}</el-checkbox>
                      </div>
                      <div class="">
                        <span class="mar-r-16 just-cur-point" @click="$emit('saveNoteToCustomer', false), noteToCustomer = false">{{ $t('common.base.no') }}</span>
                        <button type="button" class="btn btn-primary base-comment-submit btn-primary-small" @click="$emit('saveNoteToCustomer', true), noteToCustomer = false">
                          {{ $t('common.base.yes') }}
                        </button>
                      </div>
                    </div>
                  </div>
                  <template #reference>
                    <el-checkbox v-model="form.toCustomer" @input="toCustomerChangeHandler" :disabled="checkboxDisabled.toCustomer" :true-label="1" :false-label="0">{{$t('common.option.commentAction[1]')}}</el-checkbox>
                  </template>
                </el-popover>
                
                <!-- 亚玛芬不显示 -->
                <template v-if="!isHasAmerPrint">
                  <el-checkbox v-model="form.cusNotice" @input="cusNoticeChangeHandler" :disabled="checkboxDisabled.cusNotice" :true-label="1" :false-label="0">{{$t('common.option.commentAction[2]')}}</el-checkbox>
                  <el-checkbox v-model="form.cusRemarksNotice" @input="cusRemarksNoticeHandler" :disabled="checkboxDisabled.cusRemarksNotice" :true-label="1" :false-label="0">{{$t('common.option.commentAction[3]')}}</el-checkbox>
                </template> 
              </template>
            </div>
            <button type="button" class="btn btn-primary base-comment-submit" @click="submit" :disabled="!allowOperate">
              {{submitText}}
            </button>
          </div>
        <!-- start 操作组 -->
        
        </div>
      <!-- end 底部操作 -->

      </div>

      <input v-show="inputState" type="file" ref="input" @change="handleChange" multiple>
      <div v-show="inputState" class="base-comment-cover" v-if="!allowOperate">
        <base-spin :text="$t('common.base.waiting')"></base-spin>
      </div>

      <div v-show="!inputState" @click.stop="getFocus" class="state-false">
        <el-input v-model="form.content" readonly :placeholder="`${placeholder}${isAt?$t('component.bizComment.placeholder2'):''}`"></el-input>
        <button type="button" class="btn btn-primary base-comment-submit" @click.stop="submit" :disabled="!allowOperate">
          {{submitText}}
        </button>
      </div>

    </div>

  </div>
</template>

<script>
/* utils */
import { getRootWindow } from '@src/util/dom';
import i18n from '@src/locales';
import { trimAll } from 'pub-bbx-utils';
import Uploader from '@src/util/uploader';
import Validator from '@src/util/validator';
import platform from '@src/platform';
import calcTextareaHeight from './calcTextareaHeight';
import _ from 'lodash'
import {enCodeAtText} from '@src/util/atText'
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
/* constant */
let EditorCalcStyle = {
  height: '82px',
  minHeight: '82px',
  overflowY:'hidden'
}



export default {
  name: 'biz-comment',
  data () {
    return {
      atUsers:[],
      // 原有参数
      checkboxDisabled: {
        showInOwn: false,
        toCustomer: false,
        cusNotice: false,
        cusRemarksNotice: false
      },
      editorCalcStyle: EditorCalcStyle,
      errMessage: '',
      editorFocus: false,
      form: this.buildForm(),
      pending: false,
      template: '',

      textClick:false,
      inputState:false,
      noteToCustomer:false,
      hideTipsCheck:false
    }
  },
  props:{
    autofocus: {
      type: Boolean,
      default: false
    },
    /** 是否禁用该组件，如果禁用不触发submit */
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: i18n.t('common.placeholder.inputContent')
    },
    /* 显示客户相关的操作 (工单/事件)有用 */
    showCustomerAction: {
      type: Boolean,
      default: false
    },
    /** 
     * @description 备注模板列表
     * 未做处理，有数据即加载
     * 格式: [ { content: '' } ]
     */
    templateList: {
      type: Array,
      default: () => []
    },
    submitText:{
      type:String,
      default: i18n.t('common.base.submit')
    },
    // 是否支持@
    isAt:{
      type:Boolean,
      default:true
    },
    userSearchUrl:{
      type:String,
      default:''
    },
    // 人员搜索格外参数（除了页码和name）
    searchParams:{
      type: Object,
      default: () => ({})
    },
    members:{
      type: Array,
      default: () => []
    },
    alwaysCheckToCustomer:{
      type:Boolean,
      default:false
    },
    hideTips:{
      type:Boolean,
      default:true
    },
  },
  inject:['initData'],
  computed: {
    // 亚马芬灰度
    isHasAmerPrint() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.AMER_PRINT ?? false;
    },
    /* 允许操作 */
    allowOperate(){
      return !this.disabled && !this.pending
    },
    /* 显示选择模板列表 */
    showSelectTemplate() {
      return Array.isArray(this.templateList) && this.templateList.length > 0;
    },
    templateListOptions() {
      return this.templateList.map(template => Object.freeze({ label: template.content, value: template.content }) )
    }
  },
  mounted(){
    document.body.addEventListener('click', this.bodyClick)
  },
  watch:{
    inputState:{
      handler(val){
        this.$emit('inputStateChange', val);
        if(this.alwaysCheckToCustomer === true){
          this.form.toCustomer = 1
          this.toCustomerChangeHandler(1, false)
        }
      },
      immediate:true
    },
    // alwaysCheckToCustomer(newValue){
    //   if(newValue === true){
    //     this.form.toCustomer = 1
    //     this.toCustomerChangeHandler(1, false)
    //   }
    // }
  },
  methods:{
    head(src) {
      if (!src) return defaultAvatar
      return src
    },
    getFocus(){
      this.inputState = true;
      this.$nextTick(()=>{
        this.$refs.editor.focus();
      });
    },
    bodyClick(){
      if(!this.textClick){
        this.inputState = false;
      }
    },
    mousedown(){
      this.textClick = true;
    },
    mouseup(){
      this.$nextTick(()=>{
        this.textClick = false;
      })
    },
    buildForm(){
      return {
        // 附件
        attachments: [],
        // 内容
        content: '',
        // 向客户发送短信
        cusNotice: 0,
        // 仅自己可见
        showInOwn: 0,
        // 客户可见
        toCustomer: 0,
        // 向客户发送短信（含备注）
        cusRemarksNotice: 0
      }
    },
    /* 向客户发送通知 变化处理 */
    cusNoticeChangeHandler(value) {
      this.checkboxDisabled.showInOwn = true;
      this.form.toCustomer = 1
    },
    /* 向客户发送通知(含备注) 变化处理 */
    cusRemarksNoticeHandler(value) {
      this.checkboxDisabled.showInOwn = true;
      this.form.toCustomer = 1;
      this.form.cusNotice = 1;
    },
    chooseFile(){
      if(this.pending) return platform.alert(i18n.t('common.base.uploadModal.tips1'))
      if(this.form.attachments.length >= Uploader.FILE_MAX_NUM) {
        return platform.alert(i18n.t('common.base.uploadModal.uploadCountTips', { count: Uploader.FILE_MAX_NUM }))
      }
        
      this.$refs.input.value = null
      this.$refs.input.click()
    },
    async deleteFile(file) {
      let index = this.form.attachments.indexOf(file)
      if(index >= 0) {
        this.form.attachments.splice(index, 1)
      }
    },
    /** 按下回车后，检测是否按住alt键，如果同时按住alt+enter提交表单 */
    enterDown(event){
      if(!event.altKey) return
      this.submit()
    },
    focus(){
      if(this.autofocus && this.$refs.editor) this.$refs.editor.focus()
    },
    handleChange(event){
      const files = event.target.files;
      if(!files || !files.length) return;

      let form = this.form;

      if(form.attachments.length + files.length > Uploader.FILE_MAX_NUM) {
        let message = i18n.t('common.base.uploadModal.uploadCountTips', { count: Uploader.FILE_MAX_NUM });
        let max = 9 - form.attachments.length;

        if(max > 0 && files.length < 9){
          message += `, ${i18n.t('common.base.uploadModal.canUploadCountTips', { count: max })}`;
        }

        return platform.alert(message)
      }

      this.pending = true;

      Uploader.batchUploadWithParse({files}).then(result => {
        let {success, error} = result;

        if(error.length > 0){
          let message = error.map(item => item.message).join('\n');
          // 此处不能return
          platform.alert(message)
        }

        if(success.length > 0){
          form.attachments = form.attachments.concat(success);
        }
      })
        .catch(err => console.error(err))
        .then(() => this.pending = false)
    },
    inputContent(event){
      let value = event.target.value;
      this.form.content = value;
      // 计算输入框大小
      this.editorCalcStyle = calcTextareaHeight(this.$refs.editor, 3, 8);
      // 验证输入内容
      if(value) this.validateContent(this.form.content);
    },
    reset(){
      this.template = ''
      this.form = this.buildForm()
      this.editorCalcStyle = EditorCalcStyle
      this.focus()
      this.resetDisabled()
    },
    resetDisabled() {
      let { checkboxDisabled } = this
      for(let key in checkboxDisabled) {
        checkboxDisabled[key] = false
      }
    },
    /**
     * @description 切换模板
    */
    async selectTemplateChange(value) {
      // 判断当前输入框中是否有内容，无内容则替换
      let { content } = this.form
      if (trimAll(content).length == 0) {
        this.template = value;
        this.form.content = value;
        this.atUsers = []
        return
      }

      let confirm = await this.$platform.confirm(i18n.t('common.base.tip.replaceCommentConfirm'));
      if(!confirm) return
      
      this.template = value;
      this.form.content = value;
      this.atUsers = []
    },
    /* 仅自己可见 变化处理 */
    showInOwnChangeHandler(value) {
      // 判断是否开始客户相关操作
      if(!this.showCustomerAction) {
        return console.warn('Caused: this.showCustomerAction is false')
      }
      if(value && this.atUsers.length > 0){
        this.$message.warning(i18n.t('common.base.tip.selfVisibleNotAtOther'))
      }
      let isDisabled = Boolean(value)
      this.checkboxDisabled.cusRemarksNotice = isDisabled
      this.checkboxDisabled.toCustomer = isDisabled
      this.checkboxDisabled.cusNotice = isDisabled
    },
    async submit(){
			this.$track.clickStat(this.$track.formatParams('DETAIL_RECORD_INFO_COMMENT'));
      try {
        if(!this.allowOperate) return;
        if(this.$refs.editor) this.$refs.editor.blur();
        // 去除前后空白
        let form = _.cloneDeep(this.form);
        if(!this.form.showInOwn){
          form.content = enCodeAtText(form.content, this.atUsers);
          form.originalContent = this.form.content
          let receivers = []
          this.atUsers.forEach(item=>{
            if(this.form.content.indexOf(`${item.displayName} `) > -1){
              receivers.push(item.userId)
            }
          })
          form.receivers = receivers.join(',')
        }

        // form.content = form.content.trimEnd();
        form.content = form.content.replace(/\s+$/g, '');

        if(!await this.validateContent(this.form.content)){
          this.inputState = false;
          this.$emit('submit', form)
        }
        else this.$message.error(i18n.t('common.base.tip.commentRequired'))
      } catch (error) {
        console.error(error)
      }
      
    },
    /* 对客户可见 变化处理 */
    toCustomerChangeHandler(value, isByUser = true) {
      let isDisabled = Boolean(value)
      this.checkboxDisabled.showInOwn = isDisabled
      if(isByUser === true){
        if(value === 1 && !this.hideTips && !this.hideTipsCheck){
          this.noteToCustomer = true
        }
        if(value === 0){
          this.noteToCustomer = false
        }
      }
      
    },
    validateContent(content){
      let field = {isNull: 0, formType: 'textarea', displayName: i18n.t('component.bizComment.content')}
      return Validator.validate(this.form.content, field).then(validateRes => {
        this.errMessage = validateRes
        return this.errMessage
      })
    },
    // 手动触发@
    addAt(){
      this.form.content = `${this.form.content}@`
      this.$refs.atTextarea.focusText()
    }
  }
}
</script>

<style lang="scss">

.btn-primary-small{
    padding:4px 12px;
    font-size:12px;
  }
.biz-comment-at{
  .tag {
    border-radius: 5px;
    background: beige;
    border: 1ps outset yellow;
  }
  
  .editor {
    width: 400px;
    height: 200px;
    overflow: auto;
    white-space: pre-wrap;
    border: solid 2px rgba(0,0,0,.5);
  }
  textarea {
    display: block;
  }
  
  .vuetify-editor {
    width: 400px;
    margin: 0;
    padding: 0;
  }
  .vuetify-editor textarea {
    height: 200px;
  }
  .v-input__slot {
    margin: 0;
  }
  .v-text-field__details {
    display: none;
  }
  
  .element-editor {
    width: 400px;
  }
  .element-editor textarea {
    height: 200px;
  }
  
  .avatar {
    max-width: 1em;
    vertical-align: middle;
  }
  textarea {
    padding: 0;
    font-size: inherit;
    resize: none;
  }
  
  /* override styles */
  .atwho-li {
    padding: 0 4px;
  }
  .atwho-li img {
    height: 100%;
    width: 36px;
    border-radius: 4px;
    -webkit-transform: scale(.8);
  }
  .atwho-li span {
    padding-left: 4px;
  }
  .biz-comment-atwho-wrap {
    display: inline-block;
    vertical-align: top;
    width: 100%;
  }


  .state-false{
    display: flex;
    border-radius: 4px;
    padding: 5px 8px;
    // background-color: #F9f9f9;
    background-color:  $bg-color-l1;
    border: 1px solid transparent;

    .el-input__inner{
      width: calc(100% - 10px);
      border: none;
      padding: 0;
      cursor: auto !important;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
      background-color: #F9f9f9 !important;
    }
  }

  .base-comment{
    position: relative;
    // border: 1px solid $color-primary;
    border: 1px solid #F9f9f9;
    z-index: 8;
    outline: none;
    border-radius: 4px;

    input[type='file']{
      display: none !important;
    }
    
    &:hover{
      border-color: $input-border-hover-color;
    }

    &:focus,
    &.base-comment-focus{
      border: 1px solid $color-primary !important;
    }
  }

  .base-comment-inner{
    background-color: #f9f9f9;
    border-radius: 4px;
  }

  .base-comment-editor{
    background-color: #f9f9f9;
    border: none;
    resize: none;
    display: block;
    margin: 0;
    width: 100%;
    padding: 5px 8px;
    line-height: 24px; 
    height: 84px;
  }

  textarea.base-comment-editor::-webkit-input-placeholder{
    color: #ccc;
  }

  textarea.base-comment-editor:-ms-input-placeholder{
    color: #ccc;
  }

  textarea.base-comment-editor::-moz-placeholder{
    color: #ccc;
  }

  .base-comment-footer{
    padding: 0 8px 5px 8px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .base-comment-tool{
    height: 24px;
    margin: 0;
    padding: 0;
    line-height: 24px;
    background-color: transparent;
    border: none;
    outline: none;
    transition: color ease .3s;
    font-size: 14px;
    color: #999;

    &:hover{
      color: $color-primary;
    }
    
    i.iconfont{
      font-size: 14px;
    }
  }

  .base-comment-bottom {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    .base-comment-title {
      color: #9a9a9a;
      padding-top: 15px;
    }

    .base-comment-action{
      display: flex;
      flex-flow: row;
      flex-wrap: wrap;
      align-items: center;

      .el-select {
        min-width: 200px;
        max-width: 400px;
        margin-right: 20px;
      }

      .el-checkbox{
        margin: 0 16px 0 0;

        .el-checkbox__label{
          padding-left: 5px;
          color: #9a9a9a;
          font-weight: normal;
        }
      }
    }
  }

  .base-comment-submit{
    margin: 0;
    font-size: 14px;
    line-height: 24px;
    height: 32px;
    padding: 3px 12px;
    border-radius: 4px;
    background-color: $color-primary;
    border: 1px solid $color-primary;
    color:#fff;

    i{
      margin-right: 2px;
    }
  }

  .base-comment-cover{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9;
    cursor: not-allowed;
    background-color: rgba(245,245,245,.65);
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
  }

  .base-comment-attachment{
    padding: 8px;
    background: #f9f9f9;

    .base-file-item:last-child{
      margin-bottom: 0;
    }
  }

  .base-comment-err{
    margin-left: 10px;
    color: $color-danger;
    font-size: 14px;
    font-weight: 500;
    line-height: 20px;
  }

  .select-template {
    padding: 8px 8px 0;
    color: $text-color-regular;
  }

  
}
</style>
